package com.gitee.cui.client.handler;

import com.gitee.cui.client.client.ClientSession;
import com.gitee.cui.common.common.ProtoInstant;
import com.gitee.cui.common.common.bean.msg.ProtoMsg;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 登录成功响应信息处理类
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/10/27 16:35
 **/
@Slf4j
@ChannelHandler.Sharable
@Service
public class LoginResponseHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    private HeartBeatClientHandler heartBeatClientHandler;

    @Autowired
    private ChatMsgHandler chatMsgHandler;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 判断消息是否有效
        if (!(msg instanceof ProtoMsg.Message)) {
            super.channelRead(ctx, msg);
            return;
        }

        // 判断消息类型
        ProtoMsg.Message message = (ProtoMsg.Message) msg;
        ProtoMsg.HeadType type = message.getType();
        if (ProtoMsg.HeadType.LOGIN_RESPONSE != type) {
            super.channelRead(ctx, msg);
            return;
        }

        // 判断登录是否成功
        ProtoMsg.LoginResponse response = message.getLoginResponse();
        ProtoInstant.ResultCodeEnum code = ProtoInstant.ResultCodeEnum.values()[response.getCode()];
        if (ProtoInstant.ResultCodeEnum.SUCCESS != code) {
            // 登录失败
            log.info(code.getDesc());
        } else {
            // 登录成功
            ClientSession.loginSuccess(ctx, message);
            ChannelPipeline pipeline = ctx.pipeline();
            pipeline.addAfter("encoder", "heartbeat", heartBeatClientHandler);
            pipeline.addAfter("encoder", "chat", chatMsgHandler);
            heartBeatClientHandler.channelActive(ctx);
        }
    }
}
